package com.zlzlib.manager.config;

import com.zlzlib.common.bean.ResultVo;
import com.zlzlib.manager.exception.ConfigException;
import com.zlzlib.manager.exception.NormalException;
import lombok.extern.log4j.Log4j2;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.Iterator;
import java.util.Set;

/**
 * 统一异常捕获
 *
 * @DateTime: 2023/3/21 10:05
 * @Author zlz
 * @Version 1.0
 */
@ControllerAdvice
@Log4j2
public abstract class BaseExceptionConfig {

    /**
     * 拦截捕捉自定义异常 ConstraintViolationException.class
     *
     * @param ex 异常
     * @return 结果
     */
    @ResponseBody
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResultVo constraintViolationExceptionHandler(ConstraintViolationException ex) {
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        StringBuilder msg = new StringBuilder();
        while (iterator.hasNext()) {
            ConstraintViolation<?> cvl = iterator.next();
            msg.append('[').append(cvl.getMessageTemplate()).append("] ");
        }
        return ResultVo.error(msg.toString());
    }

    @ResponseBody
    @ExceptionHandler(value = {MethodArgumentNotValidException.class, BindException.class})
    public ResultVo constraintViolationExceptionHandler(BindException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder msg = new StringBuilder();
        for (ObjectError error : bindingResult.getAllErrors()) {
            msg.append('[').append(error.getDefaultMessage()).append("] ");
        }
        return ResultVo.error(msg.toString());
    }

    @ResponseBody
    @ExceptionHandler(value = UndeclaredThrowableException.class)
    public ResultVo undeclaredThrowableExceptionHandler(UndeclaredThrowableException e) {
        String msg = e.getCause() == null ? e.getMessage() : e.getCause().getMessage();
        return ResultVo.error(msg);
    }

    @ResponseBody
    @ExceptionHandler(value = ConfigException.class)
    public ResultVo normalExceptionHandler(ConfigException e) {
        return ResultVo.error(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = NormalException.class)
    public ResultVo normalExceptionHandler(NormalException e) {
        return ResultVo.error(e.getMessage());
    }

    /**
     * 拦截所有请求错误
     *
     * @param e 异常
     * @return 结果
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResultVo systemExceptionHandler(Exception e) {
        log.error(e, e);
        //判断数据库错误
        if (e instanceof DataIntegrityViolationException) {
            return ResultVo.error("数据操作异常，请检查当前操作数据是否满足限制条件!");
        }
        return ResultVo.error("系统异常,请稍后重试!");
    }

}
